/**
 * @description router module
 * @author Zhangbin
 */
import { Commit } from 'vuex'
import { RouterType, RouterStateType } from '@/store/types'
import * as types from '@/store/mutation-types'
import { getMenuApi } from '@/api/menu'
import { userStore } from '@/store/modules/user'
import { routes } from '@/router'
import { message } from 'ant-design-vue'

// 过滤路由
export const filterAsyncRoutes = (iRoutes: RouterType): RouterType => {
  iRoutes.forEach(route => {
    const component = route.component
    if (component) {
      try {
        // 判断本地是否存在该组件
        route.component = () => import(`@/views/${component}.vue`) // require(`@/views/${route.moudle}.vue`).default
      } catch (e) {
        throw new Error(e)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRoutes(route.children)
    }
  })
  return iRoutes
}

// 格式化菜单数据
const formatMenu = (menus: any[]) => {
  menus.forEach(menu => {
    try {
      menu.meta = JSON.parse(menu.meta);
      if(menu.children?.length) {
        formatMenu(menu.children)
      }
    } catch (error) {
      menu.meta = {}
    }
  });
  return menus
}

const state: RouterStateType = {
  asyncRoutes: [],
  routes: []
};

const mutations = {
  [types.ASYNC_ROUTER](state: RouterStateType, payload: RouterType) {
    let asyncRoutes = filterAsyncRoutes(payload);
    // 404 页面
    asyncRoutes.push({
      path: '/:pathMatch(.*)*', name: 'NotFound', redirect: '/404', meta: { hidden: true }
    });
   
    //
    state.routes = routes.concat(asyncRoutes)
    state.asyncRoutes = asyncRoutes
  },
  [types.CLEAR_ROUTER](state: RouterStateType) {
    state.asyncRoutes = [];
    state.routes = []
  }
};

const actions = {
  [types.ASYNC_ROUTER]: async (context: { commit: Commit, state: RouterStateType }, payload: any) => {
    const res = await getMenuApi({ token: userStore.state.token });
    try {
      if (res.data.code === 0 && res.data.data.length) {
        const data = formatMenu(res.data.data);
        context.commit(types.ASYNC_ROUTER, data)
      } else {
        message.error('菜单权限获取失败！');
        throw new Error('请确认该用户菜单权限！')
      }
    } catch (error) {
      throw new Error('请确认该用户菜单权限！')
    }
    
  }
};


export const routerStore = {
  state,
  mutations,
  actions
}